const fs = require('fs');  
const path = require('path');  
const logger = require('../util/logger');
const SVGIcons2SVGFontStream = require('svgicons2svgfont'); 

module.exports = function(opt) {
  let unicodeStart = opt.unicodeStart;
  let glyphList = [];
  return new Promise((resolve, reject) => {
    const fontStream = new SVGIcons2SVGFontStream({
      fontName: opt.fontName,
      normalize: true,
      log: opt.successLog ? logger.info : function() {},
      ...opt.svgicons2svgfont,
    });
    fontStream.pipe(fs.createWriteStream(opt.svgPath)).on('finish', function() {
      resolve(glyphList);
    }).on('error', function(err) {
      reject(err);
    });

    opt.files.forEach(file => {
      if (!/\.svg$/i.test(file)) return;
      unicodeStart += 1;
      let glyph = fs.createReadStream(file);
      let code = String.fromCharCode(unicodeStart);
      let name = file.replace(/.*\/([^/]+)\.svg/i, '$1');
      glyph.metadata = {
        unicode: [code],  
        name: name
      };
      glyphList.push({ name, code: unicodeStart });
      fontStream.write(glyph);
    });
    fontStream.end();
  });
};

